<template>
  <PageWrapper dense>
    <CollapseContainer title="价格">
      <BasicForm @register="registerForm">
        <!-- 价格区间 -->
        <template #priceList>
          <div class="w-full px-6 flex gap-8px">
            <a-button @click="handleInsert">新增</a-button>
            <a-button danger @click="handleRemoveSelect">选中删除</a-button>
          </div>
          <VxeBasicTable ref="tableRef" v-bind="gridOptions" />
        </template>
        <!-- 制版费 -->
        <template #plateCost>
          <a-input v-model:value="state.spuExtraInfo.plateCost">
            <template #addonAfter>
              <Select v-model:value="state.spuExtraInfo.plateCostUnitId" style="width: 80px">
                <SelectOption v-for="item in getDictOptions(DictEnum.PRICE_CODE)" :key="item.value"
                  >{{ item.label }}
                </SelectOption>
              </Select>
            </template>
          </a-input>
        </template>
      </BasicForm>
    </CollapseContainer>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { BasicForm, useForm } from '@/components/Form';
  import { ref, reactive } from 'vue';
  import { drawerSchemas3, vxeTableColumns, validRules } from '../product.data';
  import { Select } from 'ant-design-vue';
  import { CollapseContainer } from '@/components/Container';
  import { PageWrapper } from '@/components/Page';
  import { DictEnum } from '@/enums/dictEnum';
  import { getDictOptions } from '@/utils/dict';
  import { BasicTableProps, VxeBasicTable } from '@/components/VxeTable';
  import { cloneDeep } from 'lodash-es';
  import type { VxeGridInstance } from 'vxe-table';

  defineOptions({ name: 'PriceEdit' });
  const SelectOption = Select.Option;
  const [registerForm, { setFieldsValue, validate }] = useForm({
    // layout: 'vertical',
    labelWidth: 100,
    name: 'user-drawer',
    showActionButtonGroup: false,
    baseColProps: { span: 12 },
    schemas: drawerSchemas3,
  });
  const state = reactive({
    spuExtraInfo: {
      plateCost: '',
      plateCostUnitId: '',
    },
  });
  const tableRef = ref<VxeGridInstance>();
  const gridOptions = reactive<BasicTableProps>({
    id: 'CodeGenVxeTable',
    keepSource: true,
    border: true,
    editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
    columns: vxeTableColumns,
    toolbarConfig: {
      enabled: false,
    },
    columnConfig: {
      resizable: true,
    },
    data: [],
    proxyConfig: {
      // 必须设置
      enabled: false,
    },
    editRules: validRules,
  });

  async function handleInsert() {
    const $table = tableRef.value;
    if ($table) {
      const record = {
        // name: '',
      };
      // 在尾部插入
      const { row: newRow } = await $table.insertAt(record, -1);
      await $table.setEditCell(newRow, 'name');
    }
  }

  function handleRemoveSelect() {
    const $table = tableRef.value;
    if ($table) {
      $table.removeCheckboxRow();
    }
  }
  async function handleTableValidate() {
    const $table = tableRef.value;
    if (!$table) {
      return;
    }
    const hasError = await $table.validate();
    if (hasError) {
      return Promise.reject(new Error('编辑表格校验失败'));
    }
    // 使用getTableData才能拿到修改后的数据
    const tableData = $table.getTableData();
    return Promise.resolve(cloneDeep(tableData.fullData));
  }
  async function handleSubmit() {
    try {
      const data = {
        ...(await validate()),
        ...state.spuExtraInfo,
        priceList: await handleTableValidate(),
      };
      return data;
    } catch (e) {
      console.log('e', e);
    } finally {
    }
  }
  const setFormData = (data: any) => {
    setFieldsValue(data);
    state.spuExtraInfo = {
      plateCost: data.plateCost || '',
      plateCostUnitId: data.plateCostUnitId || '',
    };
    gridOptions.data = data.priceList;
  };
  defineExpose({ handleSubmit, setFormData });
</script>
